<!--
 * @Description:
 * @Author: jiannan.lv
 * @Date: 2020-06-29 13:23:25
 * @LastEditTime: 2020-11-12 16:31:30
 * @LastEditors: Please set LastEditors
-->
<template>
  <edit-drawer
    v-model:visible="showState"
    title="重置密码"
    show-submit
    submit-text="重置"
    :submit-loading="resetLoading"
    @submit="handleReset"
    @cancel="handleClose"
  >
    <dynamics-form ref="formRef" :setting="setting" :model="model" />
  </edit-drawer>
</template>
<script>
import { reactive, ref } from 'vue'
import {
  DynamicsForm, EditDrawer, libs, message
} from '@bairong/vix'
import { updateUserApi } from '@api/author'

export default {
  name: 'ResetPasswardDialog',
  components: {
    DynamicsForm,
    EditDrawer
  },
  setup() {
    const showState = ref(false)

    const model = reactive({
      password: ''
    })

    const setting = ref([
      {
        name: 'password',
        label: '重置密码',
        type: 'password',
        placeholder: '请输入重置密码',
        rules: [
          {
            required: true,
            whitespace: true,
            message: '请输入重置密码',
            trigger: 'blur'
          },
          {
            pattern: /^[a-zA-Z0-9-*/+.~!@#$%^&*()]{6,20}$/,
            message: '请输入六位字符、数字、或符号',
            trigger: 'blur'
          }
        ]
      }
    ])
    const resetLoading = ref(false)
    const formRef = ref(null)
    const currentRow = ref(null)

    const show = data => {
      showState.value = true
      currentRow.value = data
    }

    const handleClose = () => {
      showState.value = false
      formRef.value.resetFields()
      currentRow.value = null
    }

    const handleReset = () => {
      formRef.value
        .validate()
        .then(() => {
          const {
            id,
            realName,
            userName,
            type,
            departmentId,
            roleIds,
            phone
          } = currentRow.value
          const password = libs.tools.md5(model.password)
          const params = {
            id,
            realName,
            userName,
            type,
            departmentId,
            roleIds,
            password,
            phone
          }
          updateUserApi(params)
            .then(() => {
              resetLoading.value = false
              handleClose()
              message.success('重置成功')
            })
            .catch(err => {
              resetLoading.value = false
              message.error(err)
            })
        })
        .catch(() => {})
    }

    return {
      formRef,
      showState,
      model,
      setting,
      resetLoading,
      handleReset,
      handleClose,
      show
    }
  }
}
</script>
